package com.ddxz.demo.quartz.task;

import com.ddxz.demo.quartz.entity.GroupEntity;
import com.ddxz.demo.quartz.service.TaskService;
import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;
import org.quartz.utils.Key;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

/**
 * class description
 *
 * @author 朱宗刚
 * @version 1.0.0
 * @date 2020/11/24
 */

@Component
public class DdxzJobManager implements ConstData {
    public void startJob(GroupEntity group) {
        JobDataMap jobDataMap = new JobDataMap();
        jobDataMap.put(GROUP_KEY, GROUP_NAME);
        jobDataMap.put(JOB_KEY, group.getJobName());
        jobDataMap.put(THREAD_KEY, service);

        JobDetail jobDetail = JobBuilder.newJob(DdxzQuartzJob.class)
                .withIdentity(group.getJobName(), GROUP_NAME)
                .usingJobData(jobDataMap)
                .build();
        CronTrigger trigger = TriggerBuilder.newTrigger()
                .withIdentity(group.getJobName(), GROUP_NAME)
                .withSchedule(CronScheduleBuilder.cronSchedule(group.getCron()))
                .build();
        try {
            Scheduler scheduler = factory.getScheduler();
            scheduler.scheduleJob(jobDetail, trigger);
            scheduler.start();
        } catch (SchedulerException se) {
            logger.error("启动失败", se);
            throw new RuntimeException(se);
        }
    }

    public void updateJob(GroupEntity entity) {
        Key key = new JobKey(entity.getJobName(), GROUP_NAME);
        try {
            Scheduler scheduler = factory.getScheduler();
            if (scheduler.getJobDetail((JobKey) key) == null) {
                return;
            }

            key = new TriggerKey(entity.getJobName(), GROUP_NAME);
            CronTrigger trigger = TriggerBuilder.newTrigger()
                    .withIdentity(entity.getJobName(), GROUP_NAME)
                    .withSchedule(CronScheduleBuilder.cronSchedule(entity.getCron()))
                    .build();

            scheduler.rescheduleJob((TriggerKey) key, trigger);
        } catch (SchedulerException se) {
            logger.error("更新失败", se);
            throw new RuntimeException(se);
        }
    }

    public void pauseJob(GroupEntity entity) {
        try {
            Scheduler scheduler = factory.getScheduler();
            JobKey key = new JobKey(entity.getJobName(), GROUP_NAME);
            if(null == scheduler.getJobDetail(key)) {
                return;
            }

            scheduler.pauseJob(key);
        } catch (SchedulerException se) {
            logger.error("暂停失败", se);
            throw new RuntimeException(se);
        }
    }

    public void resumeJob(GroupEntity entity) {
        try{
            Scheduler scheduler = factory.getScheduler();
            JobKey key = new JobKey(entity.getJobName(), GROUP_NAME);
            if(null == scheduler.getJobDetail(key)) {
                return;
            }

            scheduler.resumeJob(key);
        } catch (SchedulerException se) {
            logger.error("恢复失败", se);
            throw new RuntimeException(se);
        }
    }

    public void removeJob(GroupEntity entity) {
        try{
            Scheduler scheduler = factory.getScheduler();
            JobKey key = new JobKey(entity.getJobName(), GROUP_NAME);
            if(null == scheduler.getJobDetail(key)) {
                return;
            }

            scheduler.deleteJob(key);
        } catch (SchedulerException se) {
            logger.error("删除失败", se);
            throw new RuntimeException(se);
        }
    }

    public void runningOnce(GroupEntity entity) {
        JobDataMap jobDataMap = new JobDataMap();
        jobDataMap.put(GROUP_KEY, ONCE_GROUP);
        jobDataMap.put(JOB_KEY, entity.getJobName());
        jobDataMap.put(THREAD_KEY, service);

        JobDetail jobDetail = JobBuilder.newJob(DdxzQuartzJob.class)
                .withIdentity(entity.getJobName(), ONCE_GROUP)
                .usingJobData(jobDataMap)
                .build();
        SimpleTrigger trigger = TriggerBuilder.newTrigger()
                .withIdentity(entity.getJobName(), ONCE_GROUP)
                .withSchedule(SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(1).withRepeatCount(0))
                .startNow()
                .build();
        try {
            Scheduler scheduler = factory.getScheduler();
            scheduler.scheduleJob(jobDetail, trigger);
            scheduler.start();
        } catch (SchedulerException se) {
            logger.error("执行失败", se);
            throw new RuntimeException(se);
        }
    }

    private final TaskService service;
    private final SchedulerFactory factory = new StdSchedulerFactory();

    private static final Logger logger = LoggerFactory.getLogger(DdxzJobManager.class);

    public DdxzJobManager(TaskService service) {
        this.service = service;
    }
}
